package com.example.jimuyutabletcontrol.heartbeatModule;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: HDX
 * @date: 2020\4\1 0001
 */
public class Heartbeat extends HeartbeatIterface {

    private static Heartbeat heartbeat;

    public static Heartbeat getInstance() {
        synchronized (Heartbeat.class) {
            if (null == heartbeat) {
                heartbeat = new Heartbeat();
            }
            return heartbeat;
        }
    }

    private ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
    /**
     * 开始心跳
     */
    @Override
    public void startHeartbeat() {
        isStop = false;
        if (threadRunning) return;
        singleThreadExecutor.execute(() -> {
            while (!isStop) {
                threadRunning = true;
                try {
                    heartBeatCount += 1;
                    sendHeartbeat();
                    Thread.sleep(heartbeatTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    isStop = true;
                }
                if (isStop) {
                    threadRunning = false;
                }
            }
        });
    }
}
